package com.redispro.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.redispro.dto.*;
import com.redispro.entity.*;
import com.redispro.mapper.BlogMapper;
import com.redispro.service.*;
import com.redispro.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 李力
 * @since 2022-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private IUserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IFollowService followService;
    //基于set实现
//    @Override
//    public Result queryDetail(Long id) {
//        //1.查询blog
//        if (id == null) {
//            return Result.fail("参数为null");
//        }
//        Blog blog = getById(id);
//        if (blog == null) {
//            return Result.fail("笔记不存在");
//        }
//        //2.查询与blog有关的对象
//        Long userId = blog.getUserId();
//        User user = userService.getById(userId);
//        //3.查询blog是否被点赞
//        isLiked(blog);
//        blog.setName(user.getNickName());
//        blog.setIcon(user.getIcon());
//        return Result.ok(blog);
//    }
//
//    private void isLiked(Blog blog) {
//        //1.获取登录用户
//        Long userId = UserHolder.getUser().getId();
//        //2.判断当前用户是否点过赞
//        Boolean isLiked = redisTemplate.opsForSet().isMember(RedisConstants.BLOG_LIKED_KEY + blog.getId(), userId.toString());
//        blog.setIsLike(BooleanUtil.isTrue(isLiked));
//    }
//
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public Result likeBlog(Long id) {
//        if (id == null) {
//            return Result.fail("参数为null");
//        }
//        //1.获取登录用户
//        Long userId = UserHolder.getUser().getId();
//        //2.判断当前用户是否点过赞
//        Boolean isLiked = redisTemplate.opsForSet().isMember(RedisConstants.BLOG_LIKED_KEY + id, userId.toString());
//        if (BooleanUtil.isFalse(isLiked)) {
//            //2.1未点赞-》点赞
//            //数据库点赞数加1
//            boolean isUpdated = update().setSql("liked=liked+1").eq("id", id).update();
//            if (isUpdated) {
//                //redis中添加给笔记点赞的用户
//                redisTemplate.opsForSet().add(RedisConstants.BLOG_LIKED_KEY + id, userId.toString());
//            }
//        } else {
//            //2.2点过赞-》取消点赞
//            boolean isUpdated = update().setSql("liked=liked-1").eq("id", id).update();
//            if (isUpdated) {
//                redisTemplate.opsForSet().remove(RedisConstants.BLOG_LIKED_KEY + id, userId.toString());
//            }
//        }
//        return Result.ok();
//    }
//
//    @Override
//    public Result queryHotBlog(Integer current) {
//        // 根据用户查询
//        Page<Blog> page = query()
//                .orderByDesc("liked")
//                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
//        // 获取当前页数据
//        List<Blog> records = page.getRecords();
//        // 查询用户
//        records.forEach(blog -> {
//            Long userId = blog.getUserId();
//            User user = userService.getById(userId);
//            //查询blog是否被点赞
//            isLiked(blog);
//            blog.setName(user.getNickName());
//            blog.setIcon(user.getIcon());
//        });
//        return Result.ok(records);
//    }


    //基于zSet实现排行榜
    @Override
    public Result queryDetail(Long id) {
        //1.查询blog
        if (id == null) {
            return Result.fail("参数为null");
        }
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在");
        }
        //2.查询与blog有关的对象
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        //3.查询blog是否被点赞
        isLiked(blog);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
        return Result.ok(blog);
    }

    private void isLiked(Blog blog) {
        //1.获取登录用户
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return;
        }
        Long userId = user.getId();
        //2.判断当前用户是否点过赞
        Double score = redisTemplate.opsForZSet().score(RedisConstants.BLOG_LIKED_KEY + blog.getId(), userId.toString());
        blog.setIsLike(score != null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result likeBlog(Long id) {
        if (id == null) {
            return Result.fail("参数为null");
        }
        //1.获取登录用户
        Long userId = UserHolder.getUser().getId();
        //2.判断当前用户是否点过赞
        Double score = redisTemplate.opsForZSet().score(RedisConstants.BLOG_LIKED_KEY + id, userId.toString());
        if (score == null) {
            //2.1未点赞-》点赞
            //数据库点赞数加1
            boolean isUpdated = update().setSql("liked=liked+1").set("update_time", new Date()).eq("id", id).update();
            if (isUpdated) {
                //redis中添加给笔记点赞的用户
                redisTemplate.opsForZSet().add(RedisConstants.BLOG_LIKED_KEY + id, userId.toString(), System.currentTimeMillis());
            }
        } else {
            //2.2点过赞-》取消点赞
            boolean isUpdated = update().setSql("liked=liked-1").set("update_time", new Date()).eq("id", id).update();
            if (isUpdated) {
                redisTemplate.opsForZSet().remove(RedisConstants.BLOG_LIKED_KEY + id, userId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            //查询blog是否被点赞
            isLiked(blog);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
        });
        return Result.ok(records);
    }


    //排行榜查询
    @Override
    public Result queryBlogLikes(Long id) {
        if (id == null) {
            return Result.fail("参数为null");
        }
        //1.查询score top5
        Set<String> range = redisTemplate.opsForZSet().range(RedisConstants.BLOG_LIKED_KEY + id, 0, 4);
        if (range == null || range.isEmpty()) {
            return Result.ok(null);
        }
        //2.解析其中的用户id
        List<Long> ids = range.stream().map(Long::valueOf).collect(Collectors.toList());
        //3.查询用户
        if (ids.isEmpty()) {
            return Result.ok(null);
        }
        List<User> users = userService.query().in("id", ids).orderByAsc("update_time").list();
        List<UserDTO> collect = users.stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
        return Result.ok(collect);
    }

    @Override
    public Result queryBlogByUserId(Integer current, Long id) {
        if (id == null) {
            return Result.fail("参数为null");
        }
        Page<Blog> blogPage = query().eq("user_id", id).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        List<Blog> records = blogPage.getRecords();
        return Result.ok(records);
    }


    //推送笔记
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveBlog(Blog blog) {
        if (blog == null) {
            return Result.fail("参数为null");
        }
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        //1.保存探店笔记
        boolean save = save(blog);
        if (!save) {
            return Result.fail("新增失败");
        }
        //2.查询作者的粉丝
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
        if (!follows.isEmpty()) {
            //3.获取粉丝的id
            for (Follow follow : follows) {
                Long fansId = follow.getUserId();
                //4推送
                String key = "feed:" + fansId;
                redisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
            }
        }
        return Result.ok(blog.getId());
    }

    //查询收件箱里面的所有笔记实现滚动分页查询
    @Override
    public Result queryBlogOf(Long max, Integer offset) {
        if (max == null) {
            return Result.fail("参数为null");
        }
        Long currentUserId = UserHolder.getUser().getId();
        //1.查询收件箱
        String key = "feed:" + currentUserId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet().reverseRangeByScoreWithScores(
                key, 0, max, offset, 3
        );
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok(null);
        }
        //2.解析结果
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            //2.1获取id
            String value = typedTuple.getValue();
            ids.add(Long.valueOf(value));
            //2.1获取分数(时间戳)
            long time = typedTuple.getScore().longValue();
            if (time == minTime) {
                os++;
            } else {
                minTime = time;
                os = 1;
            }
        }
        //3.查询blog
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last(
                "order by field(id," + idStr + ")"
        ).list();

        for (Blog blog : blogs) {
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            isLiked(blog);
        }
        //4.封装返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);
    }
}
